using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks; // Added for TaskCanceledException

namespace WindowsFormsDataBaice
{
    public class LoginForm : Form
    {
        private TextBox txtUsername;
        private TextBox txtPassword;
        private CheckBox chkRememberPassword;
        private Button btnLogin;
        private Label lblTitle;
        private Label lblUsername;
        private Label lblPassword;
        private Panel mainPanel;
        private HttpClient httpClient;

        // 登录响应数据类
        public class LoginResponse
        {
            public string msg { get; set; }
            public int code { get; set; }
            public LoginData data { get; set; }
        }

        public class LoginData
        {
            public AccountMessage accMsg { get; set; }
            public string toKen { get; set; }
        }

        public class AccountMessage
        {
            public int id { get; set; }
            public string name { get; set; }
            public string pwd { get; set; }
            public string realName { get; set; }
            public bool isState { get; set; }
            public DateTime createTime { get; set; }
            public int[] roleIds { get; set; }
            public string[] roleName { get; set; }
        }

        public LoginForm()
        {
            InitializeComponent();
            httpClient = new HttpClient();
            LoadSavedCredentials();
        }

        private void InitializeComponent()
        {
            this.Text = "系统登录";
            this.Size = new Size(600, 700);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = Color.FromArgb(240, 244, 248);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 主面板 - 添加渐变效果
            mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.White,
                Padding = new Padding(60)
            };

            // 标题
            lblTitle = new Label
            {
                Text = "🏥 医院管理系统",
                Font = new Font("微软雅黑", 32, FontStyle.Bold),
                ForeColor = Color.FromArgb(52, 152, 219),
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Top,
                Height = 120
            };

            // 副标题
            var lblSubtitle = new Label
            {
                Text = "Hospital Management System",
                Font = new Font("微软雅黑", 12, FontStyle.Regular),
                ForeColor = Color.FromArgb(127, 140, 141),
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Top,
                Height = 30
            };

            // 用户名标签
            lblUsername = new Label
            {
                Text = $"{IconManager.Icons.User}  用户名",
                Font = new Font("微软雅黑", 14, FontStyle.Regular),
                ForeColor = Color.FromArgb(52, 73, 94),
                AutoSize = true,
                Location = new Point(80, 180)
            };

            // 用户名输入框
            txtUsername = new TextBox
            {
                Location = new Point(80, 220),
                Size = new Size(400, 45),
                Font = new Font("微软雅黑", 14, FontStyle.Regular),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.FromArgb(248, 249, 250),
                ForeColor = Color.FromArgb(52, 73, 94)
            };

            // 密码标签
            lblPassword = new Label
            {
                Text = $"{IconManager.Icons.Lock}  密码",
                Font = new Font("微软雅黑", 14, FontStyle.Regular),
                ForeColor = Color.FromArgb(52, 73, 94),
                AutoSize = true,
                Location = new Point(80, 290)
            };

            // 密码输入框
            txtPassword = new TextBox
            {
                Location = new Point(80, 330),
                Size = new Size(400, 45),
                Font = new Font("微软雅黑", 14, FontStyle.Regular),
                UseSystemPasswordChar = true,
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.FromArgb(248, 249, 250),
                ForeColor = Color.FromArgb(52, 73, 94)
            };

            // 记住密码复选框
            chkRememberPassword = new CheckBox
            {
                Text = "记住密码",
                Font = new Font("微软雅黑", 12, FontStyle.Regular),
                ForeColor = Color.FromArgb(127, 140, 141),
                Location = new Point(80, 400),
                AutoSize = true
            };

            // 登录按钮
            btnLogin = new Button
            {
                Text = $"{IconManager.Icons.Login}  登录",
                Size = new Size(400, 55),
                Location = new Point(80, 460),
                Font = new Font("微软雅黑", 16, FontStyle.Bold),
                ForeColor = Color.White,
                BackColor = Color.FromArgb(52, 152, 219),
                FlatStyle = FlatStyle.Flat,
                Cursor = Cursors.Hand
            };
            btnLogin.FlatAppearance.BorderSize = 0;
            btnLogin.Click += BtnLogin_Click;

            // 添加鼠标悬停效果
            btnLogin.MouseEnter += (s, e) => btnLogin.BackColor = Color.FromArgb(41, 128, 185);
            btnLogin.MouseLeave += (s, e) => btnLogin.BackColor = Color.FromArgb(52, 152, 219);

            // 添加控件
            mainPanel.Controls.Add(lblTitle);
            mainPanel.Controls.Add(lblSubtitle);
            mainPanel.Controls.Add(lblUsername);
            mainPanel.Controls.Add(txtUsername);
            mainPanel.Controls.Add(lblPassword);
            mainPanel.Controls.Add(txtPassword);
            mainPanel.Controls.Add(chkRememberPassword);
            mainPanel.Controls.Add(btnLogin);

            this.Controls.Add(mainPanel);

            // 绑定回车键事件
            this.AcceptButton = btnLogin;
            txtPassword.KeyPress += (s, e) =>
            {
                if (e.KeyChar == (char)Keys.Enter)
                {
                    btnLogin.PerformClick();
                }
            };
        }

        private async void BtnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsername.Text.Trim()) || string.IsNullOrEmpty(txtPassword.Text.Trim()))
            {
                MessageBox.Show("请输入用户名和密码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            btnLogin.Enabled = false;
            btnLogin.Text = "登录中...";

            try
            {
                // 设置请求头
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                httpClient.DefaultRequestHeaders.Add("User-Agent", "HospitalManagementSystem/1.0");

                // 构建GET请求URL，将参数作为查询字符串
                var queryParams = $"Name={Uri.EscapeDataString(txtUsername.Text.Trim())}&Pwd={Uri.EscapeDataString(txtPassword.Text.Trim())}";
                var requestUrl = $"http://101.201.170.32:5011/api/Account/Login?{queryParams}";

                // 添加调试信息
                Console.WriteLine($"发送GET请求到: {requestUrl}");

                var response = await httpClient.GetAsync(requestUrl);
                var responseContent = await response.Content.ReadAsStringAsync();

                Console.WriteLine($"响应状态: {response.StatusCode}");
                Console.WriteLine($"响应内容: {responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(responseContent);
                    
                    if (loginResponse.code == 200)
                    {
                        // 保存登录信息
                        SaveLoginInfo(loginResponse.data);
                        
                        // 保存记住密码设置
                        SaveRememberPassword();
                        
                        MessageBox.Show($"欢迎 {loginResponse.data.accMsg.realName}！", "登录成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 打开主窗体，传递登录信息
                        var mainForm = new MainForm(
                            loginResponse.data.accMsg.id,
                            loginResponse.data.accMsg.name,
                            loginResponse.data.accMsg.realName,
                            loginResponse.data.accMsg.roleName
                        );
                        mainForm.Show();
                        
                        // 隐藏登录窗体
                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show(loginResponse.msg, "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    string errorMessage = $"网络请求失败: {response.StatusCode}";
                    if (!string.IsNullOrEmpty(responseContent))
                    {
                        errorMessage += $"\n详细信息: {responseContent}";
                    }
                    MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络连接失败: {ex.Message}\n请检查API服务是否启动", "连接错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (TaskCanceledException ex)
            {
                MessageBox.Show($"请求超时: {ex.Message}\n请检查网络连接", "超时错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"登录异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnLogin.Enabled = true;
                btnLogin.Text = "登录";
            }
        }

        private void SaveLoginInfo(LoginData loginData)
        {
            try
            {
                var loginInfo = new
                {
                    UserId = loginData.accMsg.id,
                    Username = loginData.accMsg.name,
                    RealName = loginData.accMsg.realName,
                    Token = loginData.toKen,
                    RoleNames = loginData.accMsg.roleName
                };

                var json = JsonConvert.SerializeObject(loginInfo);
                File.WriteAllText("login_info.json", json);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存登录信息失败: {ex.Message}");
            }
        }

        private void SaveRememberPassword()
        {
            try
            {
                var rememberData = new
                {
                    RememberPassword = chkRememberPassword.Checked,
                    Username = chkRememberPassword.Checked ? txtUsername.Text.Trim() : "",
                    Password = chkRememberPassword.Checked ? txtPassword.Text.Trim() : ""
                };

                var json = JsonConvert.SerializeObject(rememberData);
                File.WriteAllText("remember_password.json", json);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存记住密码设置失败: {ex.Message}");
            }
        }

        private void LoadSavedCredentials()
        {
            try
            {
                if (File.Exists("remember_password.json"))
                {
                    var json = File.ReadAllText("remember_password.json");
                    var rememberData = JsonConvert.DeserializeObject<dynamic>(json);
                    
                    if (rememberData.RememberPassword == true)
                    {
                        chkRememberPassword.Checked = true;
                        txtUsername.Text = rememberData.Username.ToString();
                        txtPassword.Text = rememberData.Password.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载保存的凭据失败: {ex.Message}");
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            httpClient?.Dispose();
        }
    }
} 